package Tool;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;

public class XMLReader {
    private static XMLReader instance;
    private Document xmlDocument;
    private Element rootNode;

    private XMLReader() {
        SAXReader configureReader = new SAXReader();
        try {
            xmlDocument = configureReader.read(new File("Configure.xml"));
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        rootNode = xmlDocument.getRootElement();
    }

    public static XMLReader getInstance() {
        if (instance == null)
            instance = new XMLReader();
        return instance;
    }

    public String getMachineTypebyID(String totalTestUnitID) {
        for (Element machine : rootNode.elements("Machine")) {
            String s = machine.element("TotalTestUnitID").getText();
            if (s.equals(totalTestUnitID)) {
                return machine.element("MachineType").getText();
            }
        }
        return null;
    }

    public String getIPbyID(String totalTestUnitID) {
        for (Element machine : rootNode.elements("Machine")) {
            String s = machine.element("TotalTestUnitID").getText();
            if (s.equals(totalTestUnitID))
                return machine.element("IP").getText();
        }
        return null;
    }

    public String getPortbyID(String totalTestUnitID) {
        for (Element machine : rootNode.elements("Machine")) {
            String s = machine.element("TotalTestUnitID").getText();
            if (s.equals(totalTestUnitID))
                return machine.element("Port").getText();
        }
        return null;
    }

    public int getTestunitNo() {
        int count = rootNode.elements().size();
        return count;
    }
}
